<template>
  <div>
    <el-dialog
      :title="`${row.id ? '编辑' : '添加'}广告分类`"
      class="edit-classify-dialog"
      :visible.sync="visible"
      :close-on-click-modal="false"
      :before-close="handleCloseDialog"
      width="900px"
    >
      <el-form
        :model="dataObject"
        :rules="rules"
        ref="adminForm"
        label-width="130px"
        size="small"
      >
        <el-form-item label="分类名称：" prop="classifyName">
          <el-input v-model="dataObject.classifyName" placeholder="请输入分类名称" clearable></el-input>
        </el-form-item>

        <el-form-item label="排序：" prop="classifySort">
          <el-input
            type="number"
            placeholder="请输入排序"
            v-model="dataObject.classifySort"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="图标：" prop="classifyPic">
          <SingleUpload
            :data="dataObject.classifyPic"
            folder="goods"
            @on-change="
              e => {
                onChange(e, 'classifyPic');
              }
            "
          />
        </el-form-item>
        <el-form-item label="背景色：" prop="pageBgColor">
          <ColorPicker
            v-model="dataObject.pageBgColor"
            :preset-colors="customPresets"
            @change="handleColorChange"
          />
        </el-form-item>
        <el-form-item label="背景图片：" prop="pageBgImage">
          <SingleUpload
            :data="dataObject.pageBgImage"
            folder="goods"
            @on-change="
              e => {
                onChange(e, 'pageBgImage');
              }
            "
          />
        </el-form-item>

        <el-form-item label="分类描述：" prop="classifyDesc">
          <el-input
            type="textarea"
            rows="5"
            show-word-limit
            maxlength="200"
            placeholder="请输入分类描述"
            v-model="dataObject.classifyDesc"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="handleConfirmDialog('adminForm')"
          size="mini"
          >确 定</el-button
        >
        <el-button @click="handleCloseDialog" size="mini">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import SingleUpload from "@/components/Upload/singleUpload.vue";
import ColorPicker from "@/components/ColorPicker/index.vue";
import { createNamespacedHelpers } from "vuex";
import { getStorage } from "@/utils/index";
import { addGoodsClassify, updateGoodsClassify } from "@/api/goods/index";
const { mapState } = createNamespacedHelpers("goods");
const defaultObject = {
  classifyName: "",
  classifySort: "1",
  classifyDesc: "",
  classifyPic: [],
  pageBgImage: [],
  pageBgColor: ""
};

export default {
  components: {
    SingleUpload,
    ColorPicker
  },
  data() {
    return {
      visible: true,
      loading: false,
      dataObject: Object.assign({}, defaultObject),
      classifyOptions: [],
      selectedColor: "#42b983",
      customPresets: ["#ff0000", "#00ff00", "#0000ff", "#ffff00"]
    };
  },
  props: {
    row: {
      type: Object,
      default: {}
    }
  },
  computed: {
    ...mapState({
      rules: state => state.rules
    })
  },
  mounted() {
    if (this.row.id) {
      let data = { ...this.row };
      Object.keys(this.dataObject).forEach(key => {
        if (key === "classifyPic" || key === "pageBgImage") {
          data[key] = data[key]
            ? [
                {
                  url: getStorage("user").filePreviewUrl + "/" + data[key],
                  filePath: data[key]
                }
              ]
            : [];
        }
        this.dataObject[key] = data[key];
      });
    }
  },
  methods: {
    handleCloseDialog() {
      this.$emit("handle-cancel");
    },
    handleConfirmDialog(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = { ...this.dataObject };
          if (params.classifyPic && params.classifyPic.length) {
            params.classifyPic = params.classifyPic[0].filePath;
          }
          if (params.pageBgImage && params.pageBgImage.length) {
            params.pageBgImage = params.pageBgImage[0].filePath;
          }
          if (this.row.id) {
            params.id = this.row.id;
            updateGoodsClassify(params).then(response => {
              this.resetForm(formName);
              this.$message({
                message: "编辑成功",
                type: "success",
                duration: 1000
              });
              this.$emit("handle-confirm");
            });

            return;
          }
          addGoodsClassify(params).then(response => {
            this.resetForm(formName);
            this.$message({
              message: "添加成功",
              type: "success",
              duration: 1000
            });
            this.$emit("handle-confirm");
          });
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dataObject = Object.assign({}, defaultObject);
    },
    // 回调组件赋值
    onChange(e, key) {
      this.dataObject[key] = e;
      this.$refs["adminForm"].validateField(key, error => {
        if (error) {
          this.$message.error(error);
        }
      });
    },
    //选中背景色
    handleColorChange(color) {
      this.dataObject.pageBgColor = color;
      this.$refs["adminForm"].validateField("pageBgColor", error => {
        if (error) {
          this.$message.error(error);
        }
      });
    }
  }
};
</script>
<style scoped>
.tips {
  font-size: 12px;
  color: #999;
}
</style>
<style lang="scss">
.edit-classify-dialog {
  .el-tag {
    cursor: pointer;
  }
}
</style>
